package com.jhinwins.equipmenteb.equipmentebserver.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jhinwins.equipmenteb.equipmentebserver.dao.InventoryDao;
import com.jhinwins.equipmenteb.equipmentebserver.dao.OrderDao;
import com.jhinwins.equipmenteb.equipmentebserver.dao.ProductDao;
import com.jhinwins.equipmenteb.equipmentebserver.dao.ProductTypeDao;
import com.jhinwins.equipmenteb.equipmentebserver.entity.*;
import com.jhinwins.equipmenteb.equipmentebserver.service.ProductService;
import com.jhinwins.equipmenteb.equipmentebserver.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class ProductServiceImpl implements ProductService {
    private ProductTypeDao productTypeDao;
    private ProductDao productDao;
    private InventoryDao inventoryDao;
    private OrderDao orderDao;
    @Value("${server.pics.dir}")
    private String picDir;

    @Autowired
    public ProductServiceImpl(ProductTypeDao productTypeDao, ProductDao productDao, InventoryDao inventoryDao, OrderDao orderDao) {
        this.productTypeDao = productTypeDao;
        this.productDao = productDao;
        this.inventoryDao = inventoryDao;
        this.orderDao = orderDao;
    }

    @Override
    public JSONArray getIndexDatas() {
        JSONArray datas = new JSONArray();
        //首先获取所有的类型，然后获取每种类型下的5个商品即可
        List<ProductTypeBean> typeBeans = Optional.of(productTypeDao.findAll()).orElse(new ArrayList<>());
        for (ProductTypeBean typeBean : typeBeans) {
            JSONObject floor = new JSONObject();
            JSONArray floorDatas = new JSONArray();
            floor.put("title", typeBean.getTypeName());
            floor.put("id", typeBean.getId());
            ProductBean productBeanExp = new ProductBean();
            productBeanExp.setProductTypeBean(new ProductTypeBean(typeBean.getId()));
            Page<ProductBean> productBeans = productDao.findAll(Example.of(productBeanExp), new PageRequest(0, 5));
            for (ProductBean productBean : productBeans) {
                JSONObject floorItem = new JSONObject();
                floorItem.put("desc", productBean.getShortDesc());
                floorItem.put("title", productBean.getName());
                floorItem.put("imgs", productBean.getProductImgBeans());
                floorItem.put("price", getPrice(productBean));
                floorDatas.add(floorItem);
            }
            floor.put("ress", floorDatas);
            datas.add(floor);
        }
        return datas;
    }

    @Override
    public JSONArray getFloorDatas(Long floorid, String keyword, Integer pageIndex, Integer pageSize) {
        //-----------------------组合筛选条件------------------------------
        ProductBean productBeanExa = new ProductBean();
        if (keyword != null && keyword.length() > 0 && !keyword.equals("ALL")) productBeanExa.setName(keyword);
        ProductTypeBean productTypeBeanExa = new ProductTypeBean();
        if (floorid != null && floorid > 0) {
            productTypeBeanExa.setId(floorid);
            productBeanExa.setProductTypeBean(productTypeBeanExa);
        }

        ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);
        //-----------------------组合筛选条件------------------------------

        Page<ProductBean> productBeans = productDao.findAll(Example.of(productBeanExa, matcher), new PageRequest(pageIndex, pageSize));

        JSONArray datas = new JSONArray();
        for (ProductBean productBean : productBeans) {
            JSONObject item = new JSONObject();
            item.put("imgs", productBean.getProductImgBeans());
            item.put("name", productBean.getName());
            item.put("desc", productBean.getShortDesc());
            item.put("specifications", productBean.getSpecificationBeans());
            item.put("id", productBean.getId());
            item.put("price", getPrice(productBean));
            datas.add(item);
        }

        return datas;
    }

    @Override
    public JSONObject getProductDatas(Long productid) {
        ProductBean productBean = productDao.findOne(productid);
        JSONObject data = new JSONObject();
        data.put("id", productBean.getId());
        data.put("name", productBean.getName());
        data.put("desc", productBean.getShortDesc());
        // TODO: 2018/3/22  
        data.put("price", getPrice(productBean));
        data.put("pics", productBean.getProductImgBeans());
        //规格
        List<SpecificationBean> specificationBeans = productBean.getSpecificationBeans();
        JSONArray specifications = new JSONArray();
        for (SpecificationBean specificationBean : specificationBeans) {
            JSONObject specificationItem = new JSONObject();
            specificationItem.put("name", specificationBean.getSpecificationName());
            specificationItem.put("stateName", specificationBean.getStateName());
            specificationItem.put("specId", specificationBean.getId());
            JSONArray opts = new JSONArray();
            for (SpecValueBean specValueBean : specificationBean.getValues()) {
                JSONObject specValue = new JSONObject();
                specValue.put("name", specValueBean.getName());
                specValue.put("value", specValueBean.getValue());
                specValue.put("specValueId", specValueBean.getId());
                opts.add(specValue);
            }
            specificationItem.put("opts", opts);
            specifications.add(specificationItem);
        }
        data.put("specifications", specifications);
        data.put("introduces", productBean.getProductIntroduce());
        return data;
    }

    @Override
    public JSONObject addProduct(ProductBean productBean) {
        ProductBean save = productDao.save(productBean);
        JSONObject data = new JSONObject();
        data.put("prodictid", save.getId());
        return data;
    }

    @Override
    public List<ProductTypeBean> allTypes() {
        return productTypeDao.findAll();
    }

    @Override
    public JSONObject addInventory(InventoryBean inventoryBean) {
        InventoryBean save = inventoryDao.save(inventoryBean);
        JSONObject data = new JSONObject();
        data.put("id", save.getId());
        return data;
    }

    @Override
    public JSONObject addToCart(ProductBean productBean, Map<SpecificationBean, SpecValueBean> specCfg, Integer tenancy, Integer count) {
        JSONObject resp = new JSONObject();
        resp.put("status", "NO_SUCH_INVENTORY");
        InventoryBean inventoryExa = new InventoryBean();
        inventoryExa.setProductBean(productBean);
        for (InventoryBean inventoryBean : inventoryDao.findAll(Example.of(inventoryExa))) {
            try {
                if (inventoryBean.getSpecCfg().size() == 0) throw new Exception();
                for (SpecificationBean specificationBean : inventoryBean.getSpecCfg().keySet()) {

                    SpecValueBean specValueBean = null;
                    for (SpecificationBean bean : specCfg.keySet()) {
                        if (bean.equals(specificationBean)) {
                            specValueBean = specCfg.get(bean);
                            break;
                        }
                    }
                    specValueBean = Optional.ofNullable(specValueBean).orElseThrow(Exception::new);

                    if (!inventoryBean.getSpecCfg().get(specificationBean).getId().equals(specValueBean.getId())) {
                        throw new Exception();
                    }
                }
            } catch (Exception e) {
                continue;
            }
            //存在库存
            if (inventoryBean.getCount() >= count) {
                resp.put("status", "SUCCESS");
                resp.put("inventoryid", inventoryBean.getId());
                //添加订单
                OrderBean orderBean = new OrderBean();
                orderBean.setState(OrderBean.STATE_UNPAID);
                orderBean.setCount(count);
                orderBean.setTenancy(tenancy);
                orderBean.setUserBean(UserUtils.curUser);
                orderBean.setTime(System.currentTimeMillis());
                orderBean.setInventoryBean(new InventoryBean(inventoryBean.getId()));
                OrderBean save = orderDao.save(orderBean);
                resp.put("orderid", save.getId());
                return resp;

            } else resp.put("status", "COUNT_TOO_LARGE");
        }
        return resp;
    }

    /**
     * 获取商品价格
     */
    private Double getPrice(ProductBean productBean) {
        InventoryBean inventoryBean = new InventoryBean();
        inventoryBean.setProductBean(new ProductBean(productBean.getId()));
        Page<InventoryBean> beans = inventoryDao.findAll(Example.of(inventoryBean), new PageRequest(0, 10));
        for (InventoryBean bean : beans) {
            return bean.getPrice();
        }
        return 0D;
    }
}
